package com.bw.controller.dc;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.dc.PiLinkman;
import com.bw.entity.dc.PiMaterial;
import com.bw.resp.ResponseResult;
import com.bw.service.dc.IPiLinkmanService;
import com.bw.utils.ExportExcel;
import com.bw.utils.ReadExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-16
 */
@RestController
    @RequestMapping("/link")
public class PiLinkmanController {

    @Autowired
    private IPiLinkmanService linkmanService;

    private final Logger logger = LoggerFactory.getLogger(PiLinkmanController.class);

    /**
     * @Description:根据id查询所有联系人
     * @Author: 李钊毅
     * @Date: 2020/6/20 9:20
     * @param id:
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("getAllLinkById/{id}")
    public ResponseResult getAllLinkById(@PathVariable("id")int id){
        logger.info("根据id查询");
        ResponseResult success = ResponseResult.SUCCESS();
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("customerId",id);
            List list = linkmanService.list(wrapper);
            logger.debug("查询结果"+list);
            success.setResult(list);
        }catch (Exception e){
            logger.error("查询失败,{}",e.toString());
            success.setSuccess(false);
            success.setMessage("查询失败"+e.toString());
        }
        logger.info("查询结束");
        return success;
    }
    /**
     * @Description:联系人查询
     * @Author: 李钊毅
     * @Date: 2020/6/16 9:35
     * @param piLinkman:
     * @return: com.bw.resp.ResponseResult
     **/
    @PutMapping("/getLinkMan/{num}/{size}")
    public ResponseResult getLinkMan(@RequestBody PiLinkman piLinkman,@PathVariable("num")int num,@PathVariable("size")int size){
        logger.info("联系人列表查询");
        ResponseResult success = ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.ne("dstatus",1);//排除已经删除的数据
            if(piLinkman.getName()!=null){
                queryWrapper.like("name","%"+piLinkman.getName()+"%");
            }
            if(piLinkman.getCustomerId()!=null){
                queryWrapper.eq("customerId",piLinkman.getCustomerId());
            }
            queryWrapper.eq("dstatus",0);
            PageHelper.startPage(num,size);
            List list = linkmanService.list(queryWrapper);
            logger.debug("列表查询"+list);
            PageInfo pageInfo = new PageInfo(list);
            success.setResult(pageInfo);
        }catch (Exception e){
            logger.error("查询失败,{}",e.toString());
            success.setSuccess(false);
            success.setMessage("查询失败"+e.toString());
        }
        logger.info("查询结束");
        return success;
    }

    /**
     * @Description:根据id查询
     * @Author: 李钊毅
     * @Date: 2020/6/16 19:28
     * @param id:
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("getOne/{id}")
    public ResponseResult getOne(@PathVariable("id")int id){
        logger.info("根据id查询");
        ResponseResult success = ResponseResult.SUCCESS();
        try {
            PiLinkman byId = linkmanService.getById(id);
            logger.debug("查询结果"+byId);
            success.setResult(byId);
        }catch (Exception e){
            logger.error("查询失败,{}",e.toString());
            success.setSuccess(false);
            success.setMessage("查询失败"+e.toString());
        }
        logger.info("查询结束");
        return success;
    }
    /**
     * @Description:根据id删除
     * @Author: 李钊毅
     * @Date: 2020/6/16 19:58
     * @param id:
     * @return: com.bw.resp.ResponseResult
     **/
    @DeleteMapping("delOne/{id}")
    public ResponseResult delOne(@PathVariable("id")int id){
        logger.info("根据id删除");
        ResponseResult success = ResponseResult.SUCCESS();
        try {
            PiLinkman byId = linkmanService.getById(id);
            byId.setDstatus(1);
            boolean b = linkmanService.saveOrUpdate(byId);
            logger.debug("删除返回值"+b);
            if(b){
                success.setMessage("删除成功");
            }else {
                success.setSuccess(false);
                success.setMessage("删除失败");
            }

        }catch (Exception e){
            logger.error("删除失败"+e.toString());
            success.setSuccess(false);
            success.setMessage("删除失败");
        }
        logger.info("删除结束");
        return success;
    }
    @PostMapping("saves")
    public ResponseResult saves(@RequestBody PiLinkman piLinkman){
        logger.info("保存/修改开始");
        ResponseResult success = ResponseResult.SUCCESS();
        try {
            if(piLinkman.getId()!=null){
                logger.info("修改开始");
                piLinkman .setDstatus(0);//默认未删除
                boolean b = linkmanService.saveOrUpdate(piLinkman);
                logger.debug("修改返回值"+b);
                if(b){
                    success.setMessage("修改成功");
                }else {
                    success.setSuccess(false);
                    success.setMessage("修改失败");
                }
            }else {
                logger.info("保存开始");
                piLinkman.setDstatus(0);
                boolean b = linkmanService.saveOrUpdate(piLinkman);
                logger.debug("保存返回值"+b);
                if(b){
                    success.setMessage("添加成功");
                }else {
                    success.setSuccess(false);
                    success.setMessage("添加失败");
                }
            }


        }catch (Exception e){
            success.setSuccess(false);
            success.setMessage("修改失败");
        }
        logger.info("保存/修改结束");
        return success;
    }

    //客户根据id查询联系人
    @PostMapping("get/{id}")
    public ResponseResult get(@PathVariable("id") BigInteger id) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("customerId",id);
            List<PiLinkman> list = linkmanService.list(queryWrapper);
            result.setResult(list);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("查询失败:" + e.toString());
        }
        return result;
    }

    /**
     * @Description:联系人导出
     * @Author: 李钊毅
     * @Date: 2020/6/18 14:58
     * @return: void
     **/
    @GetMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("dstatus",0);
        List<PiLinkman> list = linkmanService.list(queryWrapper);
        String path="xls/linkman.xls";
        ExportExcel.exportExcel(response,list,"联系人列表",path);
    }
/**
 * @Description:联系人导入
 * @Author: 李钊毅
 * @Date: 2020/6/21 20:14
 * @param file:
 * @return: com.bw.resp.ResponseResult
 **/
    @PostMapping("/imporExcel")
    public ResponseResult imporExcel(MultipartFile file) {
        logger.info("原材料导入开始");
        ResponseResult re = new ResponseResult(false, 400, "上传失败");
        try {
            //获取后缀
            String hou = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'), file.getOriginalFilename().length());
            InputStream in = file.getInputStream();
            //调用封装工具类，处理数据
            List<Map> readExcel = ReadExcel.readExcel(hou, in);
            String jsonString = JSON.toJSONString(readExcel);//转成string
            System.out.println(jsonString);
            List<PiLinkman> plist = JSON.parseArray(jsonString, PiLinkman.class);//转成对象集合
            //保存
            linkmanService.saveBatch(plist);
            re.setSuccess(true);
            re.setMessage("上传成功");
            logger.info("联系人导入结束");
            return re;
        } catch (Exception e) {
            logger.error("联系人导入失败,{}",e.toString());
            return re;
        }
    }
}
